# -*- coding:utf-8 -*-
# Created by Jin(jinzhencheng@outlook.com) at 2018/8/6 16:35

from bd_spider.config import SpiderConfig
from bd_spider.config import GenerationConfig
from bd_spider.util.browser import BrowserFactory
from bd_spider.util import logger

import time

__the_logger = logger.get_logger()

__browser_factory = BrowserFactory()
global browser

def init_browser():
    global browser
    browser = __browser_factory.create()

def quit_browser():
    __browser_factory.quit(browser)

def request(url, cookies=None):
    try:
        browser.get(url)
        if cookies:
            browser.delete_all_cookies()
            browser.add_cookie(cookies)
    except Exception, e:
        __the_logger.error("phantomjs error, detail: %s" % e.message)
        quit_browser()
        __the_logger.error("=== restart phantomjs ===")
        init_browser()
        time.sleep(GenerationConfig.DEFAULT_WAIT_TIME)

def response():
    browser.implicitly_wait(SpiderConfig.REQUEST_WAIT_TIME)
    browser.set_page_load_timeout(SpiderConfig.REQUEST_WAIT_TIME)
    source = browser.page_source
    final_url = browser.current_url # Maybe redirect to other url, so 'final_url' been defined.(Jin 2018/08/14)
    return final_url, source

